<template>


  <div>

    <el-row>


      <el-col :span="12">
        <el-button @click="toAdd">添加</el-button>

      </el-col>
      <!--      <el-col :span="12"><div class="grid-content ep-bg-purple-dark" /></el-col>-->
    </el-row>


    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="userid" label="userid" width="100" />
      <el-table-column prop="username" label="username" width="100" />
      <!-- <el-table-column prop="password" label="password" /> -->
      <el-table-column prop="nickname" label="nickname" />
      <el-table-column prop="expire" label="expire" />
      <el-table-column prop="lastlogin" label="lastlogin" />
      <!-- <el-table-column prop="deptId" label="deptId" /> -->
      <el-table-column prop="deptName" label="deptName" />
      <el-table-column prop="levelName" label="levelName" />
      <!-- <el-table-column prop="registLevel" label="registLevel" /> -->
      <!-- <el-table-column prop="createtime" label="createtime" /> -->
      <el-table-column prop="userid" label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="deleteById(scope.row.userid)">删除</el-button>
          <el-button link type="primary" @click="toEdit(scope.row.userid)">修改</el-button>
          <el-button link type="primary" @click="toGrant(scope.row)">授权角色</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination v-model:current-page="queryParam.current" :page-sizes="[3, 5, 10, 15, 20, 30, 40]"
      v-model:page-size="queryParam.size" size="default" layout="sizes, prev, pager, next" :total="total"
      @size-change="loadDataList" @current-change="loadDataList" />


    <el-dialog title="用户添加" width="600px" v-model="showEdit">

      <el-form :model="form" label-width="auto">
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password" show-password />
        </el-form-item>
        <el-form-item label="过期时间">
          <!-- <el-input v-model="form.expire" /> -->

          <el-date-picker v-model="form.expire" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择一个过期时间" />
        </el-form-item>

        <el-form-item label="昵称">
          <el-input v-model="form.nickname" />
        </el-form-item>

        <el-form-item label="部门">
          <!-- <el-input v-model="form.deptId" /> -->

          <el-select v-model="form.deptId" placeholder="请选择">
            <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
          </el-select>


          <!-- <div v-for="dept in deptList">
            {{ dept }}
          </div> -->
        </el-form-item>



        <el-form-item label="挂号级别">

          <el-select v-model="form.registLevel" placeholder="请选择">
            <el-option v-for="level in levelList" :key="level.levelId" :label="level.caption" :value="level.levelId" />
          </el-select>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="closeDialog()">Cancel</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>




    <el-dialog title="给用户授权" width="700px" v-model="showGrantRole">

      用户名:{{ grantForm.username }}


      <div>
        <el-table :data="roleList" border style="width: 100%" @selection-change="selectRole" ref="grantRoleRef">
          <el-table-column type="selection" />
          <!-- <el-table-column prop="roleId" label="roleId" width="180" /> -->
          <el-table-column prop="roleName" label="roleName" width="180" />
          <el-table-column prop="createtime" label="createtime" />
        </el-table>
      </div>


      <el-button type="primary" @click="grant">授权</el-button>
      <el-button @click="showGrantRole = false">取消</el-button>

    </el-dialog>

  </div>


</template>


<script lang="ts" setup name="User">

import { ref, onMounted, reactive, nextTick } from 'vue'
import { service } from "@/utils/request";
import { useRouter } from 'vue-router'
import { page, deleteById as del, queryById, saveOrUpdate, list, type PageInfo } from '@/utils/crud'
import { ElMessage, ElMessageBox } from 'element-plus'

interface User {
  userid?: string;
  username: string;
  password: string;
  nickname: string;
  expire: string;
  lastlogin: string;
  deptId: string;
  deptName?: string | undefined;
  registLevel: string;
  createtime?: string;
  roleIds?: []
}
const tableData = ref<User[]>();//用户表格的数据
const roleList = ref<User[]>();//查询所有角色

const loading = ref(false)
const queryParam = reactive({
  current: 1,
  size: 10,
});
const total = ref(0);

const form = reactive<User>({
  username: '',
  password: '',
  nickname: '',
  expire: '',
  lastlogin: '',
  deptId: '',
  deptName: '',
  registLevel: ''
})
const grantForm = reactive({
  username: '',
  userid: '',
  roleIds: []
})
const showEdit = ref(false);
const showGrantRole = ref(false);

const router = useRouter();


const deptList = ref([]);
const levelList = ref([]);
const grantRoleRef = ref(null);
function initPage() {
  service.get('/user/initPage',).then(resp => {
    deptList.value = resp.deptList
    levelList.value = resp.levelList
  });
}

function loadDataList() {

  // 为给定 ID 的 user 创建请求
  //data  真实的数据
  // service.get<PageInfo<User>>('/user/page', { params: queryParam }).then(function (page) {
  //   tableData.value = page.data;
  //   total.value = page.total;
  // })

  page<User>('/user/page', queryParam).then(function (page) {
    tableData.value = page.data;
    total.value = page.total;
    loading.value = false;
  })

}


function deleteById(id: string) {
  ElMessageBox.confirm(
    '是否删除数据?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      del('/user/delete', id).then(function (success) {
        if (success) {
          ElMessage({
            message: '删除成功',
            type: 'success'
          })

          loadDataList();
        } else {
          ElMessage({
            message: '删除失败',
            type: 'error'
          })

        }
      })
    })
}

function save() {

  saveOrUpdate('/user/save', form).then(function (success) {
    if (success) {
      ElMessage({
        message: '保存成功',
        type: 'success'
      })
      closeDialog();
      loadDataList();
    } else {
      ElMessage({
        message: '保存失败',
        type: 'error'
      })
    }

  })
}


function toAdd() {
  showEdit.value = true
  delete form.userid;

  form.username = '';
  form.password = '';
  form.nickname = '';
  form.expire = '';
  form.deptId = '';
  form.deptName = '';
  form.registLevel = '';


}

function toEdit(id: string) {


  //根据主键查询 数据 放到  form 表单
  queryById<User>('/user/getById', id).then((vo) => {

    showEdit.value = true;

    form.userid = vo.userid
    form.username = vo.username
    form.password = vo.password
    form.nickname = vo.nickname
    form.expire = vo.expire
    // form.lastlogin = vo.lastlogin
    form.deptId = vo.deptId
    form.deptName = vo.deptName
    form.registLevel = vo.registLevel

    console.log('form', form)
  })

}

function closeDialog() {
  showEdit.value = false
}


function selectRole(selectedRoles: any) {

  console.log("selectedRoles", selectedRoles);

  grantForm.roleIds = [];
  selectedRoles.forEach((role: any) => {
    grantForm.roleIds.push(role.roleId);
  });


  // console.log("grantForm.roleIds", grantForm.roleIds);


}


/**
 * 
 * @param userId 给用户授权
 */
function toGrant(user: User) {
  grantForm.userid = user.userid;
  grantForm.username = user.username
  list<object>('/user/listRoleByUserId', { userid: user.userid }).then(function (res) {
    roleList.value = res.roleList;


    // [3,5]
    let grantedRole = [];
    //已授权的角色
    // console.log("res.userRoleList", );
    res.userRoleList.forEach((item) => {
      grantedRole.push(item.roleId);
    })


    //   "3,5"
    let grantedRoleStr = grantedRole.join(",");


    showGrantRole.value = true;


    //等dialog页面渲染完 
    nextTick(() => {
      console.log("grantRoleRef.value", grantRoleRef.value);
      roleList.value?.forEach(role => {

        if (grantedRoleStr.indexOf(role.roleId) != -1) {
          grantRoleRef.value.toggleRowSelection(role, true)
        }
      })

    })




  })
}

function grant() {
  // roleIds

  saveOrUpdate('/user/grant', grantForm).then(function (success) {
    // showGrantRole.value = false;
    // loadDataList();
    if (success) {
      showGrantRole.value = false;
      ElMessage({
        message: '授权成功',
        type: 'success'
      })
    } else {
      ElMessage({
        message: '授权失败',
        type: 'error'
      })
    }
  })

}
onMounted(() => {
  // 获取数据
  loadDataList();

  initPage()

})


</script>
